package com.wenyu.wenyuyuedu.fragment.personagefragment;


import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnNetWorkErrorListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.util.RecyclerViewStateUtils;
import com.github.jdsjlzx.view.LoadingFooter;
import com.wenyu.wenyuyuedu.R;
import com.wenyu.wenyuyuedu.activity.LoginActivity;
import com.wenyu.wenyuyuedu.activity.homepage.MyAttentionActivity;
import com.wenyu.wenyuyuedu.activity.personage.Help_FeedBack_Activity;
import com.wenyu.wenyuyuedu.adapter.circleAdapter.ListApdaters;
import com.wenyu.wenyuyuedu.bean.circle.CircleDetailBean;
import com.wenyu.wenyuyuedu.global.ApiWrapper;
import com.wenyu.wenyuyuedu.server.circle.MyCircleServer;
import com.wenyu.wenyuyuedu.utils.AbSharedUtil;
import com.wenyu.wenyuyuedu.utils.MyToast;
import com.wenyu.wenyuyuedu.utils.SharedConstants;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * A simple {@link Fragment} subclass.
 * 我的书圈的详情页--神呐
 */
public class Help_Notice_Fragment extends Fragment {


    @InjectView(R.id.fragment_list_rv)
    LRecyclerView recyclerView;
    @InjectView(R.id.iv_defult)
    ImageView ivDefult;
    private Intent intent;
    private int circleid;
    private int page = 1;
    private Help_FeedBack_Activity activity;
    private String token;
    private List<CircleDetailBean.InfoBeanX.InfoBean> info;
    private ListApdaters adapter;
    private LRecyclerViewAdapter lRecyclerViewAdapter;
    private CircleDetailBean.InfoBeanX infoBeanX;
    private String circle_uid;

    public Help_Notice_Fragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_notice, container, false);
        ButterKnife.inject(this, view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setHasFixedSize(true);
        adapter = new ListApdaters(getActivity());
        lRecyclerViewAdapter = new LRecyclerViewAdapter(adapter);
        recyclerView.setAdapter(lRecyclerViewAdapter);
        initView();
        requestData();
        RefreshAndLoadMore();
        return view;
    }

    /*获取网络数据*/
    private void requestData() {
        token = AbSharedUtil.getString(getActivity(), SharedConstants.USER_TOKEN);
        if (token == null) {
            showLoginDialog();
        } else {
            MyCircleServer myCircleServer = ApiWrapper.getInstance().create(MyCircleServer.class);
            Call<CircleDetailBean> circleDetail = myCircleServer.getCircleDetail(token, circleid, 2, page);
            circleDetail.enqueue(new Callback<CircleDetailBean>() {
                @Override
                public void onResponse(Call<CircleDetailBean> call, Response<CircleDetailBean> response) {
                    CircleDetailBean body = response.body();
                    if (body != null) {
                        int code = body.getCode();
                        if (code == 1) {
                            info = body.getInfo().getInfo();
                            infoBeanX = body.getInfo();
                             /*当前登陆用户的uid*/
                            String user_uid = body.getUser_uid();
                            circle_uid = body.getInfo().getCircle_uid();
                            if (Help_Notice_Fragment.this.info != null) {
                                if (isRefresh) {
                                    //下拉刷新
                                    adapter.clear();
                                }
                                isRefresh = false;
                                adapter.addAll(Help_Notice_Fragment.this.info);
                                adapter.getUserUid(user_uid, token, circle_uid);
                                lRecyclerViewAdapter.notifyDataSetChanged();
                            } else {
                                ivDefult.setVisibility(View.VISIBLE);
                            }
                        } else if (code == 0) {
                            /*token错误或者已经失效*/
                            showLoginDialog();
                        } else if (code == 3500) {
                                /*需要登陆后才可以操作*/
                        } else if (code == 3501) {
                            /*您必须要先加入书圈之后才可以查看哦！*/

                        } else if (code == 3502) {
                            /*所有的评论已经全部加载完毕！*/
                            recyclerView.setNoMore(true);
                        } else if (code == 3503) {
                            /*还没有产生神贴*/
                            ivDefult.setVisibility(View.VISIBLE);
                        }
                        recyclerView.refreshComplete(page);
                    }

                }

                @Override
                public void onFailure(Call<CircleDetailBean> call, Throwable t) {
                    MyToast.showToast(getActivity(), "数据异常，请稍后重试", Toast.LENGTH_SHORT);
                    ivDefult.setVisibility(View.VISIBLE);
                    netError();
                }
            });
        }
    }

    AlertDialog ad;
    private TextView quxiao;
    private TextView queding;

    /*token错误或者已失效*/
    private void showLoginDialog() {
        ad = new AlertDialog.Builder(getActivity()).create();
        ad.show();
        Window window = ad.getWindow();
        window.setContentView(R.layout.dailog_login);
        quxiao = (TextView) window.findViewById(R.id.dialog_login_quxiao);
        queding = (TextView) window.findViewById(R.id.dialog_login_queding);
        quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ad.dismiss();
                getActivity().finish();
            }
        });
        queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
                ad.dismiss();
                getActivity().finish();
            }
        });
    }

    /*
      * 下拉刷新加载更多
      * */
    private void RefreshAndLoadMore() {
        recyclerView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.Normal);
                //  listAdapter.clear();
                // lRecyclerViewAdapter.notifyDataSetChanged();
                isRefresh = true;
                requestData();
            }
        });
        recyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {

                if (isRefresh) {
                    return;
                }
                page++;
                requestData();
            }
        });
        lRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                List<CircleDetailBean.InfoBeanX.InfoBean> dataList = adapter.getDataList();
                intent.setClass(getActivity(), MyAttentionActivity.class);
                //对应帖子的id
                intent.putExtra("allattentionid", dataList.get(position).getId());
                //对应圈子的昵称
                intent.putExtra("allattentiontitle", infoBeanX.getPubTitle());
                //发帖人的昵称
                intent.putExtra("allattentionnickname", dataList.get(position).getMember().getNickname());
                /*对应发帖人的uid*/
                intent.putExtra("allattentionnicknameuid", dataList.get(position).getUid());
                 /*创建圈子人的uid*/
                intent.putExtra("create_circle_uid",circle_uid);
                startActivity(intent);
            }
        });
       /* lRecyclerViewAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public void onItemLongClick(View view, int position) {
                MyToast.showToast(getActivity(), "长安" + position, Toast.LENGTH_SHORT);
            }
        });*/
        recyclerView.setLScrollListener(new LRecyclerView.LScrollListener() {
            /*
            * 向上滑动的监听事件；
            * */
            @Override
            public void onScrollUp() {
                activity.hideIndyamic();
            }

            /*
            * 向下滑动的监听事件；
            * */
            @Override
            public void onScrollDown() {
                activity.showIndyamic();
            }

            /*
            * 正在滚动的监听事件；
            * */
            @Override
            public void onScrolled(int distanceX, int distanceY) {

            }

            /*
            * 正在滚动的监听事件；
            * */
            @Override
            public void onScrollStateChanged(int state) {

            }
        });
        recyclerView.setFooterViewHint("正在加载中...", "没有更多数据了", "网络请求失败");
        recyclerView.setFooterViewColor(R.color.footview_text_color,R.color.footview_text_color,R.color.footview_back);
    }

    private boolean isRefresh = false;

    /**
     * 网路请求失败时的操作
     */
    private void netError() {
        isRefresh = false;
        recyclerView.refreshComplete(page);
        recyclerView.setOnNetWorkErrorListener(new OnNetWorkErrorListener() {
            @Override
            public void reload() {
                requestData();
            }
        });
    }

    /*初始化数据*/
    private void initView() {
        intent = getActivity().getIntent();
        String circleIds = intent.getStringExtra("circleId");
        circleid = Integer.parseInt(circleIds);
        activity = (Help_FeedBack_Activity) getActivity();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

}
